import React from 'react'; 
import FolderBar from "./FolderBar";
import ToolBar from "./ToolBar";
import SearchTable from "./SearchTable";
import DetailTab from"./DetailTab";
import ActivityTab from "./ActivityTab";
import FolderStore from "../stores/FolderStore";
import OptionStore from "../stores/OptionStore";
export default React.createClass({
    getInitialState: function () {
        return {                
            selectedObject: null,
            toolBarContext: null,         
            mounting: false,
            searchResult : [],
            currentPage : 0,         
            colsOption: OptionStore.getColsOption(),     
            searchStatus: "The search to find 0 matching files",
            searchKey: {}
        };
    },    
    updateDetail: function(selectedObject){
        if (!this.state.mounting) return;
        this.setState({selectedObject: selectedObject});
    },
    updataToolBar: function(toolBarContext) {
        if (!this.state.mounting) return;
        this.setState({toolBarContext: toolBarContext});
    },     
    onSelectedObjectChanged: function(event, data){
        if (!this.state.mounting) return;
        this.updateDetail(data);
        this.updataToolBar(data);     
    },
    handleSearch: function(){   
        var searchContext = this.props.location.state;
        if (!searchContext || searchContext.keyword.length === 0) return;
        $("#keyword").val(searchContext.keyword);
        var _this = this;          
        var keyword = searchContext.keyword;   
        $("#search-div").loading();     
        this.state.searchContext = searchContext;
        CMISService.doSearch(keyword).done(function(searchResult) {               
            _this.showResult(searchResult.data, 1);               
        })
        .always(function(){
            $("#search-div").endLoad();   
        });        
    },
    onDocumentRemoved: function (event, data) {
        var newResult = _.reject(this.state.searchResult, function(doc){
           return (data.id == doc.id);
        });         
        this.showResult(newResult, this.state.currentPage);
        if (this.state.selectedObject && data.id == this.state.selectedObject.id){
            this.setState({selectedObject: null});
        }

        if (this.state.toolBarContext && data.id == this.state.toolBarContext.id){
            this.setState({toolBarContext: null});
        }
    },
    showResult: function(searchResult, currentPage) {
        if (!this.state.mounting) return; 
        var  _this = this;      

        $("#btn-addSmartFolder").show();

        this.setState({
            searchResult: searchResult,
            currentPage: currentPage             
        });     

        this.setState({
            searchStatus: "The search to find {0} matching files".format(searchResult.length)
        });          
        if (searchResult.length === 0) {
           $('#pager').empty();
        } 
        else {
            var options = {
                currentPage: currentPage,
                totalPages: parseInt((searchResult.length + 9) / 10),
                bootstrapMajorVersion: 3,
                alignment: 'right',
                onPageClicked: function(e, originalEvent, type, page) {
                    _this.showResult(searchResult, page);
                }
            };
            $('#pager').bootstrapPaginator(options);
        }          
    },    
    onColsOptionChanged: function(){           
        this.setState({colsOption: OptionStore.getColsOption()});
    },
    componentDidMount: function(){
        this.state.mounting = true;
        window.resizable();           
        var _this = this;         
        FolderStore.selectedObjectChanged(this.onSelectedObjectChanged);
        FolderStore.documentRemoved(this.onDocumentRemoved);
        OptionStore.colsOptionChanged(this.onColsOptionChanged);
        if (window.ArchiveStyle) {
            $('.resi-right').css(window.ArchiveStyle.resiRightStyle);
            $('.resi-left').css(window.ArchiveStyle.resiLeftStyle);
            $('.btn_hide_split_view_master_wrap').css(window.ArchiveStyle.hideBtnStyle);
        }              

        this.handleSearch();              
       
    },  
    componentWillUnmount:function(){
        FolderStore.selectedObjectChanged(this.onSelectedObjectChanged, false);            
        FolderStore.documentRemoved(this.onDocumentRemoved, false);
        OptionStore.colsOptionChanged(this.onColsOptionChanged, false);
        window.ArchiveStyle = {};
        window.ArchiveStyle.resiRightStyle = {
            'display' : $('.resi-right')[0].style.display,
            'width' :  $('.resi-right').css('width')
        };
        window.ArchiveStyle.resiLeftStyle = {
            'width' : $('.resi-left').css('width')
        };            
        var $hidtBtn = $('.btn_hide_split_view_master_wrap');
        window.ArchiveStyle.hideBtnStyle = {
            'color': $hidtBtn.css('color'),
            'background-color': $hidtBtn.css('background-color'),
            'border-color': $hidtBtn.css('border-color')
        };            

        this.state.mounting = false;                                       
    },    
    componentWillReceiveProps: function(nextProps){
       this.handleSearch();
    },
    gotoRoot: function(){
        this.props.history.pushState(null, "/archive");
    },
    addSmartFolder: function(){
        window.addSmartFolder(this.state.searchContext);
    },
    render: function () { 
        var DetailTabItem; 
        var ToolBarItem;
        var NameItem;
            
        var FolderBarItem=(
                <div id="folder-bar" className="breadcrumb_wrap pull-left">
                    <ul className="breadcrumb n-p m-bot0 font-si16">
                        <li onClick={this.gotoRoot}>
                            <a href="javascript:void(0)">
                                <span style={{lineHeight:'16px'}} >My archives</span>
                            </a>
                        </li>
                        <li>
                            <a>
                                <span style={{lineHeight:'16px', cursor:"default"}} >{this.state.searchStatus}</span>
                            </a>
                        </li>                            
                        <button id="btn-addSmartFolder" onClick={this.addSmartFolder} style={{marginLeft:'20px',display:'none'}} type="button" className="btn btn-white btn-sm save">
                            Save as smart folder
                        </button>
                    </ul>
                    
                </div>)                
              
        if (this.state.selectedObject) {
            DetailTabItem=(<DetailTab data={this.state.selectedObject}></DetailTab>) 
            NameItem=(<span style={{fontSize: '18px'}} className="break-word">
                        <i className={classNames({
                            "fa-folder": this.state.selectedObject.type === "cmis:folder",
                            "fa-file-text-o": this.state.selectedObject.type !== "cmis:folder"}, "fa")}></i>
                        <span className="break-word">{this.state.selectedObject.name}</span>
                      </span>)              
        }             
        return (            
            <div>
                <div className="toolbar_wrap">
                    <div className="ba-col-r">  
                        {FolderBarItem}                           
                        <ToolBar data={this.state.toolBarContext} colsOption={this.state.colsOption}></ToolBar>
                    </div>   
                </div>
                <div className="root_right_wrap wrap">
                <div className="minmaxwidth resizable resizable1 resi-left ui-resizable">
                    <div className="split_view_master_wrap" >
                        <div id="search-div" style={{overflow:'auto'}} className="maillist_content_wrap_absolute_full" >
                            <SearchTable data={this.state.searchResult} colsOption={this.state.colsOption} startIdx={(this.state.currentPage - 1) * 10} endIdx={(this.state.currentPage) * 10}></SearchTable>
                            <ul id = "pager" className="pull-right" style={{marginTop: 0}}></ul>
                        </div>  
                    </div>
                </div>
                <div className="resizable resizable2 resi-right" style={{display:'inline-block'}}>      
                    <section className="split_view_slave_wrap scroll_auto_y">
                        <section className="panel">
                            <header className="panel-heading" style={{lineHeight: '36px'}}>
                                {NameItem}
                                <span className="pull-right hide-i">
                                    <i className="fa fa-times"></i>
                                </span>
                            </header>
                            <div className="doc-det-act panel-body m-top-15 row">
                                <header className="panel-head">
                                    <ul className="nav nav-justified ">
                                        <li className="active">
                                            <a href="#details" data-toggle="tab" aria-expanded="true">
                                               Details
                                            </a>
                                        </li>
                                        <li className="">
                                            <a href="#activity" data-toggle="tab" aria-expanded="false">
                                                Activity
                                            </a>
                                        </li>
                                    </ul>
                                </header>
                                <div className="panel-body">
                                    <div className="tab-content tasi-tab">                                
                                        {DetailTabItem} 
                                        <ActivityTab></ActivityTab>                              
                                    </div>
                                </div>
                            </div>
                        </section>
                    </section>
                </div>
            </div>    
        </div>     
        )            
    }
});
 
